gameInfo = {
    roomId: null,
    thisUserId: null,
    thatUserId: null,
    isWhite: true,
}
//////////////////////////////////////////////////
// 设定界⾯显⽰相关操作
//////////////////////////////////////////////////
function setScreenText(me) {
    let screen = document.querySelector('#screen');
    if (me) {
        screen.innerHTML = "轮到你落⼦了!";
    } else {
        screen.innerHTML = "轮到对⽅落⼦了!";
    }
}
//////////////////////////////////////////////////
// 初始化 websocket
let webSocketUrl = "ws://"+location.host+"/game_room"
let websocket = new WebSocket(webSocketUrl)
//////////////////////////////////////////////////
// TODO
websocket.onopen = function() {
    console.log("websocket onopen")
}

websocket.onerror = function() {
    console.log("websocket onerror")
}

websocket.onmessage = function(event) {
    console.log("[handlerGameReady]" + event.data)
    let response = JSON.parse(event.data)

    if (!response.ok) {
        alert("连接游戏失败！ reason: " + response.reason)
        location.replace("/game_hall.html")
        return
    }

    if (response.message == "gameReady") {
        gameInfo.roomId = response.roomId;
        gameInfo.thisUserId = response.thisUserId;
        gameInfo.thatUserId = response.thatUserId;
        gameInfo.isWhite = (response.whiteUser == response.thisUserId);

        initGame();

        setScreenText(gameInfo.isWhite);
        return
    } else if (response.message == 'repeatConnection') {
        alert("检测到游戏多开");
        location.replace("/login.html");
    }

    

}

window.onbeforeunload = function() {
    websocket.close()
}


websocket.onclose = function() {
    console.log("websocket onclose")

}

//////////////////////////////////////////////////
// 初始化⼀局游戏
//////////////////////////////////////////////////
function initGame() {
// 是我下还是对⽅下. 根据服务器分配的先后⼿情况决定
    let me = gameInfo.isWhite;
// 游戏是否结束
    let over = false;
    let chessBoard = [];
//初始化chessBord数组(表⽰棋盘的数组)
    for (let i = 0; i < 15; i++) {
        chessBoard[i] = [];
        for (let j = 0; j < 15; j++) {
            chessBoard[i][j] = 0;
        }
    }
    let chess = document.querySelector('#chess');
    let context = chess.getContext('2d');
    context.strokeStyle = "#BFBFBF";
// 背景图⽚
    let logo = new Image();
    logo.src = "image/sky.jpeg";
    logo.onload = function () {
        context.drawImage(logo, 0, 0, 450, 450);
        initChessBoard();
    }
// 绘制棋盘⽹格
    function initChessBoard() {
        for (let i = 0; i < 15; i++) {
            context.moveTo(15 + i * 30, 15);
            context.lineTo(15 + i * 30, 430);
            context.stroke();
            context.moveTo(15, 15 + i * 30);
            context.lineTo(435, 15 + i * 30);
            context.stroke();
        }
    }
// 绘制⼀个棋⼦, me 为 true
    function oneStep(i, j, isWhite) {
        context.beginPath();
        context.arc(15 + i * 30, 15 + j * 30, 13, 0, 2 * Math.PI);
        context.closePath();
        var gradient = context.createRadialGradient(15 + i * 30 + 2, 15 + j *
            30 - 2, 13, 15 + i * 30 + 2, 15 + j * 30 - 2, 0);
        if (!isWhite) {
            gradient.addColorStop(0, "#0A0A0A");
            gradient.addColorStop(1, "#636766");
        } else {
            gradient.addColorStop(0, "#D1D1D1");
            gradient.addColorStop(1, "#F9F9F9");
        }
        context.fillStyle = gradient;
        context.fill();
    }
    chess.onclick = function (e) {
        if (over) {
            return;
        }
        if (!me) {
            return;
        }
        let x = e.offsetX;
        let y = e.offsetY;
// 注意, 横坐标是列, 纵坐标是⾏
        let col = Math.floor(x / 30);
        let row = Math.floor(y / 30);
        if (chessBoard[row][col] == 0) {
// TODO 发送坐标给服务器, 服务器要返回结果
        send(row,col);
            //服务端响应后画棋子
//             oneStep(col, row, gameInfo.isWhite);
//             chessBoard[row][col] = 1;
        }
    }
// TODO 实现发送落⼦请求逻辑, 和处理落⼦响应逻辑.
    function send(row, col) {
        let request = {
            message: 'putChess',
            userId: gameInfo.thisUserId,
            row: row,
            col: col,
        }
        websocket.send(JSON.stringify(request));
    }

    websocket.onmessage = function (event) {
        console.log("[handlerPutChess]" + event.data)
        let response = JSON.parse(event.data);
        if (response.message != "putChess") {
            console.log("【handlerPutChess】 响应类型错误"+response.message);
            return
        }

        //判断此响应是谁落子
        if (response.userId == gameInfo.thisUserId) {
            //自己落的子，
            //根据自己的颜色绘制一个棋子
            oneStep(response.col, response.row, gameInfo.isWhite);
        } else if (response.userId == gameInfo.thatUserId) {
            //对手落子
            oneStep(response.col, response.row, !gameInfo.isWhite);
        } else {
            console.log("[handlerPutChess] response userId 错误" +response.userId );
            return;
        }

        //对应位置绘制棋子
        chessBoard[response.row][response.col] = 1;

        //交换双方落子轮次
        me = !me;
        setScreenText(me)

        //判断游戏是否结束
        let screenDiv = document.querySelector('#screen');
        if (response.winner != 0) {
            if (response.winner == gameInfo.thisUserId) {
                //alert('你赢了!');
                screenDiv.innerHTML = '你赢了!';

            } else if (response.winner == gameInfo.thatUserId) {
               //alert('你输了!');
                screenDiv.innerHTML = '你输了!';
            } else {
                //alert("winner 字段错误! " + response.winner);
                screenDiv.innerHTML = 'winner 字段错误! ' + response.winner;
            }
            //回到游戏大厅
            let backButton = document.createElement("button");
            backButton.innerHTML = '返回大厅';
            backButton.id = "backButton";
            let fatherDiv = document.querySelector('.container div');
            fatherDiv.appendChild(backButton);
            backButton.onclick = function () {
                //location.assign("/game_hall.html");
                location.replace('/game_hall.html');
            }
        }
    }
}
